var mongoose = require('mongoose');
var async=require('async');
const DataModel = require('../models/news.model');
const comment=require('../models/comment.model');

exports.create = function(req,res,next){
    const dataModel = new DataModel(req.body);

    dataModel.save()
        .then(data=>{
        res.json(data);
    })
}

exports.get = function(req,res,next){
    var id = req.params.id;
    DataModel.findById(id, function (err, data) {
        res.json(data);
    })
}

exports.update = function(req,res,next){
    const id = req.params.id;

    DataModel.findByIdAndUpdate(id, {$set: req.body}, {new:false})
        .then(data=>{
        res.json(data);
})
}

exports.getnews = function(req,res,next){
    const id = req.params.id;
    var ids = [];
    DataModel.findOne({_id: id},function(err,doc){
        if(doc){
            ids = [doc._id];
            doc.getChildren().then(function(docs){
                for(var i=0;i<docs.length;i++){
                    ids.push(docs[i]._id);
                }
                DataModel.find({ _id : {$in : ids}})
                    .then(data=>{
                    res.json({"msg":"deletes success","status":200});
            })
            });
        }
    })
}

exports.deletes = function(req,res,next){
    var idarr=req.body.idarr;
    if(idarr.length>0){
        var s=idarr.split(",");
        DataModel.remove({_id:{$in:s}})
            .then(data=> {
            res.json({"msg":"success","status":200});
    })
    }else {
        res.json({"msg":"faild","status":404});
    }
}

exports.remove = function(req,res,next){
    const id = req.params.id;

    DataModel.findByIdAndRemove(id,function(err,data){
        res.json(data);
    })

}

exports.lists = function (req, res, next) {
    var ids = req.body.categoryId.split(",");
    if (ids.length > 0) {
        DataModel.find({categoryId: {$in: ids}}).then(data=> {
            async.map(data,function (news,done) {
                comment.count({articleId:news._id},function (err,count) {
                    if(err){
                        return;
                    }else {
                        news.commentCount=count;
                        done();
                    }
                })
            },function (err) {
                res.json(data);
            })
        })
    } else {
        res.json({"msg": "请求失败", "status": 404})
    }
}


exports.list = function(req,res,next){
    var page = (req.body.page) ? req.body.page : 1;
    var rows = (req.body.rows) ? req.body.rows : 10;
    var queryCondition = {};
    if(req.body.title && req.body.title.trim().length>0){
        title = req.body.title;
        queryCondition = {
            "title" : new RegExp(title, 'i')
        }
    }
    if(req.body.categoryId && req.body.categoryId.trim().length>0){
        categoryId = req.body.categoryId;
        // Object.assign对象合并
        queryCondition = Object.assign(queryCondition,
            {
                categoryId: categoryId
            }
        )
    }
    if(req.body.content && req.body.content.trim().length>0){
        content = req.body.content;
        // Object.assign对象合并
        queryCondition = Object.assign(queryCondition,
            {
                content: content
            }
        )
    }
    // DataModel.find(queryCondition,(err,data)=>{
    //     if(err){
    //         res.json({"msg":"faild","status":404});
    //     }else{
    //         // var len=data.length;
    //         // var countArr=[];
    //         // for(var i=0;i<len;i++){
    //         //     comment.count({articleId:data[i]._id},function(err,count){
    //         //         if(err){
    //         //             return
    //         //         }else{
    //         //             countArr.push(count);
    //         //         }
    //         //     })
    //         // }
    //         // console.log(countArr);
            
    //         res.json(data);
    //     }
    // }).sort({ _id: -1 });
   DataModel.paginate(queryCondition, {sort: { _id: -1 }, page: parseInt(page), limit: parseInt(rows) },
    function(err, result) {
        // res.json(result)
        async.map(result.docs,function (news,done) {
            comment.count({articleId:news._id},function (err,count) {
                if(err){
                    return;
                }else {
                    news.commentCount=count;
                    done();
                }
            })
        },function (err) {
            result.rows = result.docs;
            delete result.docs;
            console.log(result);
            res.json(result);
        })
    });        
}